package com.web709.util;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;

/**
 * 短信发送工具类
 */
@Component
@Slf4j
public class SMSUtils {

	@Value("${aliyun.sms.accessKeyId}")
	private String accessKeyId;

	@Value("${aliyun.sms.accessKeySecret}")
	private String accessKeySecret;
	
	@Value("${aliyun.sms.signName}")
	private String signName;

	@Value("${aliyun.sms.templateCode}")
	private String templateCode;

	/**
	 * 发送短信
	 * @param phoneNumbers 手机号
	 * @param param 验证码参数
	 */
	public void sendMessage(String phoneNumbers,String param){
		log.info("Attempting to send SMS to: {}, code: {}, using signName: {}, templateCode: {}", 
				 phoneNumbers, param, signName, templateCode);
		log.debug("Using AccessKeyId: {}", accessKeyId); // Be cautious logging secrets, even at debug level

		// 校验配置是否加载成功
		if (accessKeyId == null || accessKeyId.isEmpty() || accessKeyId.equals("YOUR_SMS_ACCESS_KEY_ID") ||
			accessKeySecret == null || accessKeySecret.isEmpty() || accessKeySecret.equals("YOUR_SMS_ACCESS_KEY_SECRET")) {
			log.error("Aliyun SMS AccessKeyId or AccessKeySecret not configured correctly in application.yml");
			throw new RuntimeException("SMS configuration error. Please check application.yml");
		}

		DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
		IAcsClient client = new DefaultAcsClient(profile);

		SendSmsRequest request = new SendSmsRequest();
//		request.setSysRegionId("cn-hangzhou"); // 通常不需要设置RegionId
		request.setPhoneNumbers(phoneNumbers);
		request.setSignName(signName); // 使用配置的签名
		request.setTemplateCode(templateCode); // 使用配置的模板Code
		// 确保参数格式正确，阿里云要求JSON格式
		request.setTemplateParam("{\"code\":\"" + param + "\"}"); 
		try {
			SendSmsResponse response = client.getAcsResponse(request);
			log.info("SMS Sent Successfully. RequestId: {}, Code: {}, Message: {}", 
					 response.getRequestId(), response.getCode(), response.getMessage());
			if (!"OK".equalsIgnoreCase(response.getCode())) {
				log.error("SMS sending failed. Aliyun Response Code: {}, Message: {}", response.getCode(), response.getMessage());
				// 可以考虑抛出自定义异常或返回错误信息
			}
		} catch (ClientException e) {
			log.error("Error sending SMS: RequestId: {}, ErrCode: {}, ErrMsg: {}", 
					  e.getRequestId(), e.getErrCode(), e.getErrMsg(), e);
			// 抛出运行时异常，让上层调用者知道发送失败
			throw new RuntimeException("Failed to send SMS due to client exception.", e);
		} catch (Exception e) {
			log.error("Unexpected error sending SMS", e);
			throw new RuntimeException("Unexpected error occurred while sending SMS.", e);
		}
	}

	// 移除不再使用的静态 createClient 方法
	// public static IAcsClient createClient() { ... }

}
